/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {
	var AE = AccessibilityExtension.ns;  

	function docTitleDisplayDetails() {}
	docTitleDisplayDetails.prototype = {
		dataElementNames : ['title'],
		columnHeaders : ['titles.title'],
		
		accessIssuesDataElementNames : ['missingOrEmptyTitle','missingOrEmptyH1','toolong', 'oneword', 'titlemissingh1words', 'titleh1wordorder', 'H1OnlyAlt'],
		accessIssuesMessages : ['titles.warnings.missingOrEmptyTitle','titles.warnings.missingOrEmptyH1', 'titles.msg.toolong', 'titles.msg.oneword', 'titles.msg.titlemissingh1words', 'titles.msg.titleh1wordorder', 'titles.msg.H1OnlyAlt'],
	}
	var docTitleDisplayDetails = new docTitleDisplayDetails();
	
	function docTitleInfo(doc, node) {
	   this.document = doc;
	   this.node = node;
	   this.parseNode();
	}
	docTitleInfo.prototype = {
	   node : null,
	   title : null,
	   h1 : null,
	   document : null,
	   missingOrEmptyTitle : false,
	   missingOrEmptyH1 : false,
	   titleh1wordorder : false,
	   toolong : false,
	   oneword : false,
	   titlemissingh1words : false,
	   titlemissingh1wordstext : "",
	   H1OnlyAlt : false,
	   toomanyh1 : false,
	   display : true,
	   displayDetails: docTitleDisplayDetails,
	   parseNode : function() {
	   try {
	      if (this.document == null) {
	         return;
	      }
	      //TODO: XPath?
          if (this.node != null) {
			this.title = cleanSpaces(this.node.textContent); //title element better just have textcontent...
	      	if (this.title.length > 60) {this.toolong = true; }
		  	if (this.title.indexOf(' ') < 0) {this.oneword = true;}
	      } else {this.title= ""; this.missingOrEmptyTitle = true;}
		  	 	    
	      var h1Nodes = new Array();
	      var mergedFrames = getAccessextPrefService().getBoolPref("fae.mergeFrames");
	      //accessext_consoleDump(mergedFrames);
	      if(mergedFrames) {
	         var documentList = accessext_getDocumentList(this.document);
	         var visibleDocs = accessext_getVisibleFrames(documentList, true);
	         //accessext_consoleDump(visibleDocs);
	         for(var i = 0; i < visibleDocs.length; i++) {
	            var tempH1s = visibleDocs[i].getElementsByTagName("h1");
	            for(var t = 0; t < tempH1s.length; t++) {
	               h1Nodes.push(tempH1s[t]);
	            }
	            //h1Nodes = h1Nodes.concat(visibleDocs[i].getElementsByTagName("h1"));
	            
	         }
	      } else {
	         h1Nodes = this.document.getElementsByTagName("h1");
	      }
	            
	      this.h1 = new Array();
	      if (h1Nodes.length >= 1) {
	         for(var i=0; i<h1Nodes.length; i++) {
	            this.h1[i] = getDisplayableTextRecursively(h1Nodes[i]);
				if (this.h1[i].length==0) this.missingOrEmptyH1 = true;
				if (this.h1[i] != '' && this.h1[i] == getDisplayableAltRecursively(h1Nodes[i])) {this.H1OnlyAlt=true;}
	         }
	      }
	      if (h1Nodes.length > 2)  this.toomanyh1 = true;
		  this.missingOrEmptyTitle = (this.title==null || this.title=="");
		  if (this.h1==null) this.missingOrEmptyH1 = true;
		  if (this.missingOrEmptyTitle == true) {this.oneword = true;}
	 	  this.getH1WordsNotInTitle();
		} catch (ex) {
			accessext_consoleDump('title parseNode exception: ', ex);
		}
	   },
	   // returns true if first lowercased, trimmed h1 is contained in the title or if there is no h1
	   // returns false if not or if there is no title
	   isH1SubsetOfTitle : function() {
	      if( this.missingOrEmptyTitle ) {
	         return false;
	      }
	      if( this.missingOrEmptyH1 ) {
	         return true;
	      }
	      return (this.title.toLowerCase().indexOf(this.h1[0].toLowerCase()) >= 0);
	   },
	   getH1WordsNotInTitle : function() { //abbr have already been expanded
			var missingwordarray = new Array();
		//	var tmp = this.title.replace(/\,|\.|\!|\(|\)|\:|\%|\?|\"|\'\s+/g, ' '); //\s Any whitespace character [ \t\n\r\f\v]
		//	neither work tmp = tmp.replace(/\/x[A-Z][A-Z]\s+/g, ' '); tmp = tmp.replace(/\&laquo;\&raquo\s+/g, ' '); 
			var tmp = this.title.replace(/[^a-z-A-Z0-9]\s+/g, ' '); 
			var titlewordsarray = tmp.toLowerCase().split(' '); 
			for(var i=0; i < this.h1.length; i++) {
				if (this.h1[i].length == 0) continue;
				tmp = this.h1[i].replace(/[^a-z-A-Z0-9]\s+/g, ' '); 
				var h1wordsarray = tmp.toLowerCase().split(' '); 
				var found;
				var lastPosInTitle = 0;
				for(var h1index =0; h1index < h1wordsarray.length; h1index++) {
					for(var j=0, found = false; j < titlewordsarray.length && !found; j++) {
						if (h1wordsarray[h1index] == titlewordsarray[j]) {
							found = true;
							if (j < lastPosInTitle) {this.titleh1wordorder = true;}
							lastPosInTitle = j;
						}
					}
					if (!found) {
						this.titlemissingh1words = true; 
						var k=0;
						while(k < missingwordarray.length && h1wordsarray[h1index] != missingwordarray[k]) {k++;}
						if (k >= missingwordarray.length) {missingwordarray[missingwordarray.length] = h1wordsarray[h1index];}
					}
				}
			}
			if (missingwordarray.length > 0) {this.titlemissingh1wordstext = missingwordarray.join(" ");}
				
	   },
	   getWarnings : function() {
	      var ret = new Array();
		  var currStd = currStandard();
		  var notApplicable = accessext_getBundleSingleString('msg.unenforced');
	      if (this.missingOrEmptyTitle) {
			  var severity = getErrMsgSeverity('titles.warnings.missingOrEmptyTitle', currStd);
			  if (severity != notApplicable) {
	         	ret.push(severity + ': ' + accessext_getBundleSingleString('titles.warnings.missingOrEmptyTitle'));
			}
	      }
	      if (this.missingOrEmptyH1) {
	 		  var severity = getErrMsgSeverity('titles.warnings.missingOrEmptyH1', currStd);
			  if (severity != notApplicable) {
	        	ret.push(severity + ': ' + accessext_getBundleSingleString('titles.warnings.missingOrEmptyH1'));
	      	}
		  }
	      if (this.toolong) {
	  		  var severity = getErrMsgSeverity('titles.msg.toolong', currStd);
			  if (severity != notApplicable) {
	        	ret.push(severity + ': ' + accessext_getBundleSingleString('titles.msg.toolong'));
			}
	      }    
	      if (this.oneword) {
	 		  var severity = getErrMsgSeverity('titles.msg.oneword', currStd);
			  if (severity != notApplicable) {
	         	ret.push(severity + ': ' + accessext_getBundleSingleString('titles.msg.oneword'));
			}
	      }    
	      if (this.titlemissingh1words) {
	 		  var severity = getErrMsgSeverity('titles.msg.titlemissingh1words', currStd);
			  if (severity != notApplicable) {
			  	var tmp = accessext_getBundleSingleString('titles.msg.titlemissingh1words');
	         	ret.push(severity + ': ' + tmp.replace('%1', this.titlemissingh1wordstext));
			}
	      }   
	      if (this.titleh1wordorder) {
	 		  var severity = getErrMsgSeverity('titles.msg.titleh1wordorder', currStd);
			  if (severity != notApplicable) {
	         	ret.push(severity + ': ' + AE.accessext_getBundleSingleString('titles.msg.titleh1wordorder'));
			}
	      }   
	      if (this.H1OnlyAlt) {
	 		  var severity = getErrMsgSeverity('titles.msg.H1OnlyAlt', currStd);
			  if (severity != notApplicable) {
	         	ret.push(severity + ': ' + accessext_getBundleSingleString('titles.msg.H1OnlyAlt'));
			}
	      }   
	      return ret;
	   },
		listDetailsInHTMLFormat : function () {
			var html = "";
			for (var findex = 0; findex < this.h1.length; findex ++) { //for each treerow
				html = html + "<li>" + this.h1[findex] + "</li>"  ;
			}
			if (html != "") { html = "<dl><dt><strong>h1(s):</strong></dt><dd><ul> " + html + "</ul></dd></dl>" }
			else {html = '&nbsp;'}
			return html;
		},
	   
	}
	
	function accessext_titleDialog () {
	   document.addEventListener("message", receiveMessage, false);
	   this.init();
	   this.initDialog();
	}
	accessext_titleDialog.prototype = {
	   dataarray : null,
	   theDoc : null,
	   theWindow : null,
	   docObject : null,
	   init : function() {
	      this.dataarray = new Array();
	   },
	   initDialog : function() {
	      this.updatePointers();
	      this.refresh();
		  accessext_loadDialogPrefs();
		  accessext_setNoteCaption();
	 	  window.focus(); //SMF 6/21/07
	   }, 
	   updatePointers : function() {
		  if (window.opener.name == 'accessext-issues') {
			var accessibilityIssuesDialog = window.opener.parent;
			this.theWindow = accessibilityIssuesDialog.opener.parent._content;			
		  } else {
			this.theWindow = window.opener.parent._content;
		  }
	      this.theDoc = this.theWindow.document; 
	   },
	   cleanUp : function() {
	      return accessext_GlobalCleanup();
	   },
	   refresh : function() {
	      this.parseDocument();
	      var titleElement = document.getElementById('title-text');
	      var h1Element = document.getElementById('h1-text');
	      if (null != titleElement) {
	         titleElement.value = this.docObject.title;
	      }
	      if (null != h1Element) {
	         for(var i=0; i<this.docObject.h1.length; i++) {
	            h1Element.value = h1Element.value + this.docObject.h1[i];
	            if( (i+1) < this.docObject.h1.length ) {
	               h1Element.value = h1Element.value + "\n";
	            }
	         }
	      }
	      var warnings = this.docObject.getWarnings();
	      var warningListElement = document.getElementById('warnings-list');
	      if (null!=warningListElement) {
		  	var disptext = '';
	         for (var j=0; j<warnings.length; j++) {
			// 	disptext += warnings[j] & '\n';
	            var listItem = document.createElement('listitem');
	            listItem.setAttribute('label',warnings[j]);
	            warningListElement.appendChild(listItem);
	         }
	       warningListElement.setAttribute("value",disptext);
	      }
	   },
	   parseDocument : function() {
//	      this.docObject = new docTitleInfo(this.theDoc);
		  var loadArray = new Array();
		  ParseDocumentForTitle(this.theDoc, loadArray);
		  this.docObject = loadArray[0];
	   }
	}
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{	
	newDocTitleInfo: function(notused, tnode) { 
		var n = new docTitleInfo(tnode.ownerDocument, tnode);
		return n; 
	},

	InitAccessibilityExt: function () {
	   var titleCaption = document.getElementById("title-caption");
	   if (titleCaption == null) return; //not in title.xul so skip this function
	   var dialog = new accessext_titleDialog();
	},
	
	ParseDocumentForTitle: function(doc, loadArray) {
		try {
		      var titleNodes = doc.getElementsByTagName("title");
	          if (titleNodes.length >= 1) {
	        	loadArray[0] = new docTitleInfo(doc, titleNodes[0]);
	          } else {
		        loadArray[0] = new docTitleInfo(doc, null);
	          }
		} catch (ex) {
			accessext_consoleDump('ParseDocumentForTitle exception: ', ex);
		}
	},
	
	receiveMessage: function(event)
	{
		if (event.data == "differentStandard") {
			accessext_loadDialogPrefs();
			accessext_setNoteCaption();
		}
	}	

});
	if (AccessibilityExtension.LIB.InitAccessibilityExt) AccessibilityExtension.LIB.InitAccessibilityExt();	
}});
